package cn.gan.loveofsoul.controller;

import cn.gan.loveofsoul.commons.result.ErrorMessage;
import cn.gan.loveofsoul.commons.result.Result;
import cn.gan.loveofsoul.commons.result.StatusCode;
import cn.gan.loveofsoul.entity.User;
import cn.gan.loveofsoul.entity.constants.UserFlagEnum;
import cn.gan.loveofsoul.entity.vo.UserVO;
import cn.gan.loveofsoul.exception.BusinessException;
import cn.gan.loveofsoul.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ganwh
 * @since 2023-10-13
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 功能描述: 修改用户信息
     *
     * @param userVO
     * @return cn.gan.loveofsoul.commons.result.Result
     * @author ganwh 2023/10/18 16:52
     */
    @PostMapping("/update")
    @ResponseBody
    public Result update(@Valid @RequestBody UserVO userVO) {
        Optional<User> optional = userService.getOptById(userVO.getUserId());
        optional.orElseThrow(() -> new BusinessException(StatusCode.NOT_FOUND, ErrorMessage.USER_NOT_EXIST));
        User user = User.userVOConvert2User(userVO);
        user.setFlag(UserFlagEnum.DISABLE.getCode());
        user.setUpdateTime(LocalDateTime.now());
        boolean b = userService.updateById(user);
        user = userService.getById(userVO.getUserId());
        Result resultBody;
        if (b) {
            resultBody = new Result(StatusCode.SUCCESS, "修改成功", User.convert2UserVO(user));
        } else {
            resultBody = new Result(StatusCode.ERROR, "修改失败，请稍后再试");
        }
        return resultBody;
    }

    @GetMapping("/get")
    @ResponseBody
    public Result get(Integer userId) {
        Optional<User> optional = userService.getOptById(userId);
        optional.orElseThrow(() -> new BusinessException(StatusCode.NOT_FOUND, ErrorMessage.USER_NOT_EXIST));
        User user = optional.get();
        return new Result(StatusCode.SUCCESS, "查询成功", User.convert2UserVO(user));
    }
}
